package com.demo.study.algorithm.leetcode.array.easy;

import com.demo.study.utils.ArrayUtil;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * LT66
 * <a href="https://leetcode.cn/problems/plus-one/description">加一</a>
 *
 * @author Baymax
 * @since 2024-11-17
 */
public class LT66 {

    @Test
    public void run() {
        ArrayUtil.printArray(plusOne2(new int[]{9}));
    }

    public int[] plusOne(int[] digits) {
        List<Integer> list = new ArrayList<>();
        for (int i = digits.length - 1; i >= 0; i--) {
            list.add(digits[i]);
        }
        list.set(0, list.get(0) + 1);
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i - 1) == 10) {
                list.set(i, list.get(i) + 1);
                list.set(i - 1, 0);
            }
        }
        if (list.get(list.size() - 1) == 10) {
            list.set(list.size() - 1, 0);
            list.add(1);
        }
        int[] result = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            result[i] = list.get(list.size() - 1 - i);
        }
        return result;
    }

    public int[] plusOnePlus(int[] digits) {
        int len = digits.length;
        for (int i = len - 1; i >= 0; i--) {
            digits[i] = (digits[i] + 1) % 10;
            if (digits[i] != 0) {
                return digits;
            }
        }
        digits = new int[len + 1];
        digits[0] = 1;
        return digits;
    }

    public int[] plusOne2(int[] digits) {
        int length = digits.length;
        digits[length - 1] = digits[length - 1] + 1;
        if (digits[length - 1] < 10) {
            return digits;
        }
        for (int i = length - 1; i >= 1; i--) {
            if (digits[i] == 10) {
                digits[i] = 0;
                digits[i -1] = digits[i -1] + 1;
            }
        }
        if (digits[0] == 10) {
            digits = new int[length + 1];
            digits[0] = 1;
        }
        return digits;
    }

    public int[] plusOne1(int[] digits) {
        String numStr = "";
        for (int num : digits) {
            numStr += num;
        }
        long total = Long.parseLong(numStr);
        total += 1;
        numStr = total + "";
        int[] result = new int[numStr.length()];
        char[] charArray = numStr.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            result[i] = charArray[i] - 48;
        }
        return result;
    }

}
